<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import type { QuestionItem } from '#/types/question';
import QuestionHeader from './question-header.vue';
import cloneDeep from 'lodash/cloneDeep';
import { QUESTION_STATUS } from '../../const';
import { $t } from '@vben/locales';

interface Props {
  question: QuestionItem;
  questionIndex: number;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  updateStatus: [questionItem: QuestionItem, status: typeof QUESTION_STATUS.ANSWERED | typeof QUESTION_STATUS.UNANSWERED | typeof QUESTION_STATUS.MARKED,isMarked?:boolean];
  updateAnswer: [questionId: string | number, answer: any];
}>();

const answers = ref<string[] | null[] | undefined[]>([]);
const isMarked = ref(false);

// 获取空白数量
const blankCount = computed(() => {
  const options = props.question.originalData?.options;
  const stem = props.question.originalData?.stem || '';

  // 如果 options 是字符串，直接解析
  if (typeof options === 'string') {
    const count = parseInt(options);
    return count > 0 ? count : 1;
  }

  // 如果 options 是数字
  if (typeof options === 'number') {
    return options > 0 ? options : 1;
  }

  // 如果 options 是对象或数组，可能需要特殊处理
  if (Array.isArray(options)) {
    return options.length || 1;
  }

  // 如果 options 为 null 或 undefined，尝试从题目干中解析空白数量
  // 查找常见的空白标记：____、[]、()、{}等
  if (!options) {
    const blankPatterns = [
      /____+/g,           // 下划线
      /\[\s*\]/g,         // 方括号
      /\(\s*\)/g,         // 圆括号  
      /\{\s*\}/g,         // 花括号
      /（\s*）/g          // 中文圆括号
    ];

    let maxCount = 0;
    blankPatterns.forEach(pattern => {
      const matches = stem.match(pattern);
      if (matches) {
        maxCount = Math.max(maxCount, matches.length);
      }
    });
    return maxCount > 0 ? maxCount : 1;
  }

  // 默认返回1，如果需要测试多个空白，可以临时返回2
  return 2; // 临时设置为2个空白用于测试
});

// 初始化答案和状态
watch(() => props.question, (newQuestion) => {
  // 初始化答案数组
  answers.value = new Array(blankCount.value).fill(null);
  if (newQuestion.answer) {
    // const answerList = JSON.parse(newQuestion.answer as string);
    const answerList = newQuestion.answer || [] as any;
    answerList.forEach((answer: any, index: number) => {
      if (index < answers.value.length) {
        answers.value[index] = typeof answer === 'string' ? answer : '';
      }
    });
  }
  isMarked.value = newQuestion.markDoubtful || false;
}, { immediate: true });

// 处理单个输入框答案变化
const handleAnswerChange = (index: number, value: string) => {
  // answers.value[index] = value;
  let newAnswers = cloneDeep(answers.value);
  emit('updateAnswer', props.question.id, newAnswers);
  const hasAnswer = answers.value.some(answer => answer?.trim?.());
  const status = hasAnswer ? QUESTION_STATUS.ANSWERED : QUESTION_STATUS.UNANSWERED;
  emit('updateStatus', props.question, status,isMarked.value);
};

// 处理存疑操作
const handleMark = () => {
  isMarked.value = !isMarked.value;
  const hasAnswer = answers.value.some(answer => answer?.trim?.());
  const status = isMarked.value ? QUESTION_STATUS.MARKED : (hasAnswer ? QUESTION_STATUS.ANSWERED : QUESTION_STATUS.UNANSWERED);
  emit('updateStatus', props.question, status,isMarked.value);
};
</script>

<template>
  <div class="pb-4" :data-question-id="question.id">
    <QuestionHeader :question-index="questionIndex" :stem="question.originalData?.stem || ''"
      :score="question.originalData?.score || 0" :is-marked="isMarked" @mark="handleMark" />

    <!-- <div v-if="question.originalData?.stemImg" class="mb-4">
      <img :src="question.originalData.stemImg" :alt="$t('examCore.questionImage')" class="max-w-full h-auto" />
    </div> -->

    <div class="mt-4 space-y-3 ml-4">
      <!-- 调试信息 -->
      <div v-for="(answer, index) in answers" :key="index" class="flex items-center space-x-2">
          <el-input v-model="answers[index]" :placeholder="$t('examCore.questions.enterAnswer')"
          @change="(value: string) => handleAnswerChange(index, value)" class="flex-1">
          <template #prepend>{{ $t('examCore.blank') }}{{ index + 1 }}</template>
        </el-input>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 所有样式已使用 Tailwind CSS */
</style>
